/**
 * 消息提示与加载工具类
 */
export default class Tips {
  /**
   * 弹出提示框
   */
  static success(title, duration = 2500) {
    setTimeout(() => {
      wx.showToast({
        title: title,
        icon: 'success',
        mask: true,
        duration: duration
      })
    }, 300)

    if (duration > 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, duration)
      })
    }
  }

  /**
   * 弹出确认窗
   */
  static confirm({ title = '', content = '', showCancel = true, confirmText = '确认', cancelText = '取消', payload = {} } = {}) {
    return new Promise((resolve, reject) => {
      wx.showModal({
        title,
        content,
        showCancel,
        confirmText,
        cancelText,
        success: res => {
          if (res.confirm) {
            resolve(payload)
          } else if (res.cancel) {
            reject(payload)
          }
        },
        fail: res => {
          reject(payload)
        }
      })
    })
  }

  static toast(title, onHide, icon = 'none') {
    setTimeout(() => {
      wx.showToast({
        title: title,
        icon: icon,
        mask: false,
        duration: 2500
      })
    }, 300)

    // 隐藏结束回调
    if (onHide) {
      setTimeout(() => {
        onHide()
      }, 2500)
    }
  }

  /**
   * 警告框
   */
  static alert(title, duration = 2500) {
    wx.showToast({
      title: title,
      image: '../assets/img/icon-alert.png',
      mask: true,
      duration: duration
    })
    if (duration > 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, duration)
      })
    }
  }

  /**
   * 错误框
   */
  static error(title, onHide) {
    wx.showToast({
      title: title,
      image: '../assets/img/icon-error.png',
      mask: true,
      duration: 2500
    })
    // 隐藏结束回调
    if (onHide) {
      setTimeout(() => {
        onHide()
      }, 2500)
    }
  }

  /**
   * 弹出加载提示
   */
  static showLoading(title = '加载中') {
    if (Tips.isLoading) {
      return
    }
    Tips.isLoading = true
    wx.showLoading({
      title: title,
      mask: true
    })
  }

  /**
   * 隐藏加载提示
   */
  static hideLoading() {
    if (Tips.isLoading) {
      Tips.isLoading = false
      wx.hideLoading()
    }
  }
}

/**
 * 静态变量，是否加载中
 */
Tips.isLoading = false
